package com.heer.gymnasium.module.main.views;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.heer.amap.utils.ToastUtil;
import com.heer.gymnasium.R;
import com.heer.gymnasium.api.ResponseData.ApiResponse;
import com.heer.gymnasium.api.SignHelper;
import com.heer.gymnasium.api.callback.BaseCallback;
import com.heer.gymnasium.base.BaseRefreshFragment;
import com.heer.gymnasium.constant.Type;
import com.heer.gymnasium.module.common.beans.GlobeBean;
import com.heer.gymnasium.module.evaluate.beans.EvaTagBean;
import com.heer.gymnasium.module.fellow.beans.MatchBean;
import com.heer.gymnasium.module.fellow.beans.MatchResponseBean;
import com.heer.gymnasium.module.fellow.views.FellowDetailActivity;
import com.heer.gymnasium.module.fellow.views.InitiateFellowActivity;
import com.heer.gymnasium.module.fellow.views.InitiateMatchActivity;
import com.heer.gymnasium.module.login.views.LoginActivity;
import com.heer.gymnasium.module.main.beans.CategoryBean;
import com.heer.gymnasium.module.main.beans.FellowListResponseBean;
import com.heer.gymnasium.module.message.beans.MsgListResponseBean;
import com.heer.gymnasium.module.store.beans.AreaBean;
import com.heer.gymnasium.module.store.views.SelectStoreActivity;
import com.heer.gymnasium.util.ImageUtil;
import com.heer.gymnasium.util.ScreenUtils;
import com.heer.gymnasium.util.StringUtils;
import com.heer.imagepick.DensityUtils;
import com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayout;
import com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayoutDirection;
import com.zhihuiyun.library.commonadapter.QuickAdapter;
import com.zhihuiyun.library.commonadapter.ViewHolder;
import com.zhihuiyun.library.view.MyGridView;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnItemClick;
import butterknife.OnItemSelected;
import butterknife.OnTouch;
import retrofit2.Call;
import retrofit2.Response;

/**
 * 拼单(约战)列表
 * Created by zy on 2018/2/22.
 */

public class FellowListFragment extends BaseRefreshFragment {
    private final static int RES_ID_ROOT = R.layout.layout_fellow_list;
    private final static int RES_ID_PARENT = R.id.layout_fellow_list_root_rl;
    private final static int RES_ID_NEW_BTN = R.id.layout_fellow_list_new_btn;
    private final static int RES_ID_DIALOG_INCLUDE = R.id.layout_fellow_list_dialog_include;
    private final static int RES_ID_DATA_PANEL = R.id.layout_fellow_list_data_panel_ll;
    private final static int RES_ID_LIST = R.id.layout_fellow_list_data_lv;
    private final static int RES_ID_FELLOW_CB = R.id.layout_fellow_list_fellow_cb;
    private final static int RES_ID_FELLOW_FL = R.id.layout_fellow_list_fellow_fl;
    private final static int RES_ID_MATCH_CB = R.id.layout_fellow_list_match_cb;
    private final static int RES_ID_MATCH_FL = R.id.layout_fellow_list_match_fl;

    private final static int RES_ID_MESSAGE_LAYOUT = R.layout.item_fellow_message;
    private final static int RES_ID_MESSAGE_LOOK = R.id.item_fellow_message_into_tv;
    private final static int RES_ID_MESSAGE_CATOGERY = R.id.item_fellow_message_catogery_iv;
    private final static int RES_ID_MESSAGE_NAME = R.id.item_fellow_message_name_tv;
    private final static int RES_ID_MESSAGE_ADDRESS = R.id.item_fellow_message_address_tv;
    private final static int RES_ID_MESSAGE_TIME = R.id.item_fellow_message_time_tv;
    private final static int RES_ID_FELLOW_ITEM = R.layout.item_fellow;
    private final static int RES_ID_FELLOW_ICON = R.id.item_fellow_icon_iv;
    private final static int RES_ID_FELLOW_NAME = R.id.item_fellow_storename_tv;
    private final static int RES_ID_FELLOW_MONEY = R.id.item_fellow_money_tv;
    private final static int RES_ID_FELLOW_ADDRESS = R.id.item_fellow_address_tv;
    private final static int RES_ID_FELLOW_TIME = R.id.item_fellow_time_tv;
    private final static int RES_ID_FELLOW_SCALE = R.id.item_fellow_scale_tv;
    private final static int RES_ID_FELLOW_ENROLL = R.id.item_fellow_enroll_tv;
    private final static int RES_ID_MATCH_ITEM = R.layout.item_match;
    private final static int RES_ID_MATCH_ITEM_ID_TIME = R.id.item_match_time_tv;
    private final static int RES_ID_MATCH_ITEM_ID_DATE = R.id.item_match_date_tv;
    private final static int RES_ID_MATCH_ITEM_ID_PRICE = R.id.item_match_price_tv;
    private final static int RES_ID_MATCH_ITEM_ID_NAME = R.id.layout_match_name_tv;
    private final static int RES_ID_MATCH_ITEM_ID_ADDRESS = R.id.item_match_address_tv;
    private final static int RES_ID_MATCH_ITEM_ID_TEAM_NAME = R.id.layout_match_team_name_tv;
    private final static int RES_ID_MATCH_ITEM_EVALUATE = R.id.layout_match_evaluate_tag;
    private final static int RES_ID_MATCH_ITEM_ICON = R.id.layout_match_icon_iv;
    private final static int RES_ID_MATCH_ITEM_GRADE_ICON = R.id.item_match_team_level_iv;
    private final static int RES_ID_MATCH_ITEM_GRADE = R.id.item_match_team_level_tv;
    private final static int RES_ID_MATCH_ITEM_TEAM_ICON = R.id.layout_match_team_iv;


    private final static int RES_ID_FELLOW = R.id.layout_reservation_fellow_iv;
    private final static int RES_ID_MATCH = R.id.layout_reservation_match_iv;

    private final static int RES_ID_DIALOG = R.layout.layout_action_type;
    private final static int FULL_SCREEN_STYLE = R.style.dialog;
    private final static int DRAWABLE_YELLOW_BORDER = R.drawable.yellow_border;
    private final static int DRAWABLE_YELLOW_BTN = R.drawable.yellow_button_bg;

    private static final int RES_ID_TYPE_ITEM = R.layout.item_hobby;
    private static final int RES_ID_TYPE_ITEM_IV = R.id.item_hobby_iv;
    private static final int RES_ID_TYPE_ITEM_TV = R.id.item_hobby_tv;
    private static final int RES_ID_TYPE_ITEM_LL = R.id.item_hobby_ll;
    private static final int RES_ID_TYPE_GV = R.id.layout_action_type_gv;

    private static final int RES_ID_FILTER_TIME = R.id.layout_fellow_list_period_sp;
    private static final int RES_ID_FILTER_AREA = R.id.layout_fellow_list_area_sp;
    private static final int RES_ID_FILTER_TYPE = R.id.layout_fellow_list_type_sp;

    private static final int RES_ID_ITEM_SPINNER_LAYOUT = R.layout.item_dropdown_white;
    private static final int RES_ID_ITEM_SPINNER_DROP_DOWN_LAYOUT = android.R.layout.simple_dropdown_item_1line;
    private static final int RES_ID_ITEM_SPINNER_TV = R.id.item_dropdown_white_type_tv;

    @BindView(RES_ID_PARENT)
    ViewGroup mViewGroup;
    @BindView(RES_ID_DIALOG_INCLUDE)
    View hiddenPanel;
    private Dialog typeDialog;
    @BindView(RES_ID_NEW_BTN)
    TextView flowButton;
    @BindView(RES_ID_REFRESH_LAYOUT)
    SwipyRefreshLayout refreshLayout;
    @BindView(RES_ID_LIST)
    ListView listView;
    @BindView(RES_ID_DATA_PANEL)
    LinearLayout dataPanel;
    @BindView(RES_ID_FELLOW_CB)
    CheckBox cbFellow;
    @BindView(RES_ID_MATCH_CB)
    CheckBox cbMatch;

    @BindView(RES_ID_FILTER_TIME)
    Spinner spTime;
    @BindView(RES_ID_FILTER_AREA)
    Spinner spArea;
    @BindView(RES_ID_FILTER_TYPE)
    Spinner spType;

    GridView gvActiveType;

    private int xDelta;
    private int yDelta;

    private int controlHeight = 0;
    private int parentHeight = 0;

    private long timestamp = -1;

    private Handler handler;
    private final static int WHAT_NEW_MESSAGE = 0x1;
    private final static int WHAT_CLEAR_MESSAGE = 0x2;
    private final static int WHAT_DILL_ADDED_MESSAGE = 0x3;
    private List<Message> messageList;
    private ArrayAdapter<GlobeBean.Tag> timeAdapter;
    private QuickAdapter<MatchBean.Item> fellowAdapter;
    private QuickAdapter<MatchBean.Item> matchAdapter;
    private ArrayAdapter<AreaBean> areaAdapter;
    private QuickAdapter<CategoryBean> typeAdapter;
    private ArrayAdapter<CategoryBean> typeSelectorAdapter;

    private List<GlobeBean.Tag> timeList;
    private List<MatchBean.Item> fellowList;
    private List<MatchBean.Item> matchList;
    private List<AreaBean> areaList;
    private List<CategoryBean> typeList, typeSelectorList;


    private int currentType;
    private int d5, d10, d15;

    private int dialogSelectedType;
    private Context context;

    private String DEFAULT_AREA;
    private String DEFAULT_SPORT_TYPE;
    private String time = "", area = "", category_id = "";
    private boolean isFirstRequst = true;

    @Override
    protected int setConvertView() {
        return RES_ID_ROOT;
    }

    @Override
    protected void init() {
        super.init();
        context = getContext();
        currentType = Type.TYPE_FELLOW;
        d5 = DensityUtils.dip2px(context, 5);
        d10 = d5 * 2;
        d15 = d5 * 3;
        DEFAULT_AREA = getResources().getString(R.string.store_area);
        DEFAULT_SPORT_TYPE = getResources().getString(R.string.gym_type);
        ScreenUtils.initScreen(getActivity());
        messageList = new ArrayList<>();
        fellowList = new ArrayList<>();
        matchList = new ArrayList<>();
        typeList = new ArrayList<>();
        timeList = new ArrayList<>();
        fillTimeSpinner();
        typeSelectorList = new ArrayList<>();
        areaList = new ArrayList<>();
        handler = new Handler() {
            @Override
            public void dispatchMessage(Message msg) {
                super.dispatchMessage(msg);
                switch (msg.what) {
                    case WHAT_NEW_MESSAGE:
                    case WHAT_DILL_ADDED_MESSAGE:
                        addMessageView();
                        break;
                    case WHAT_CLEAR_MESSAGE:
                        removeMessageView((View) msg.obj);
                        break;
                }
            }
        };

        fellowAdapter = new QuickAdapter<MatchBean.Item>(context, RES_ID_FELLOW_ITEM, fellowList) {
            @Override
            public void bindData4View(ViewHolder holder, final MatchBean.Item data, int pos) {
                if (pos == 0) {
                    holder.getParentView().setPadding(0, d10, 0, d10);
                } else {
                    holder.getParentView().setPadding(0, 0, 0, d10);
                }
                ImageUtil.loadUrl(context, data.getCategoryIcon(), R.drawable.ic_small_golf, (ImageView) holder.getView(RES_ID_FELLOW_ICON));
                holder.setText(RES_ID_FELLOW_NAME, data.getStadiumname());
                holder.setText(RES_ID_FELLOW_ADDRESS, data.getPlace_name());
                holder.setText(RES_ID_FELLOW_TIME, StringUtils.timeStamp10ToDate(data.getEtime(), StringUtils.DATE_FORMAT) +
                        " " + StringUtils.getWeekOfDate(StringUtils.toLong(data.getEtime())) + " " + StringUtils.timeStamp10ToDate(data.getEtime(), "HH:mm"));
                holder.setText(RES_ID_FELLOW_MONEY, data.getPay_money() + "元/人");
                holder.setText(RES_ID_FELLOW_SCALE, data.getCurrentNum() + "/" + data.getTotalNum());
                holder.getParentView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        FellowDetailActivity.startActivity(context, Type.TYPE_FELLOW, data.getOrder_id());
                    }
                });
            }
        };

        matchAdapter = new QuickAdapter<MatchBean.Item>(context, RES_ID_MATCH_ITEM, matchList) {
            @Override
            public void bindData4View(ViewHolder holder, final MatchBean.Item data, final int pos) {
                if (pos == 0) {
                    holder.getParentView().setPadding(0, d10, 0, d10);
                } else {
                    holder.getParentView().setPadding(0, 0, 0, d10);
                }
//                MyGridView gridView = holder.getView(RES_ID_MATCH_ITEM_EVALUATE_GV);
                final ArrayList<EvaTagBean> evaluateArr = new ArrayList<>();
                if (data.getTag_me() != null && data.getTag_me().size() > 0) {
                    for (String tag : data.getTag_me()) {
                        EvaTagBean evaTagBean = new EvaTagBean();
                        evaTagBean.setName(tag);
//                        evaTagBean.setSelect(true);
                        evaTagBean.setOwn(true);
                        evaluateArr.add(evaTagBean);
                    }
                }
                if (data.getTag_other() != null && data.getTag_other().size() > 0) {
                    for (String tag : data.getTag_other()) {
                        EvaTagBean evaTagBean = new EvaTagBean();
                        evaTagBean.setName(tag);
//                        evaTagBean.setSelect(false);
                        evaluateArr.add(evaTagBean);
                    }
                }
                holder.setText(RES_ID_MATCH_ITEM_ID_TIME, StringUtils.timeStamp10ToDate(data.getStime(), "HH:mm"));
                holder.setText(RES_ID_MATCH_ITEM_ID_DATE, StringUtils.timeStamp10ToDate(data.getStime(), "yyyy-MM-dd"));
                holder.setText(RES_ID_MATCH_ITEM_ID_NAME, data.getStadiumname());
                holder.setText(RES_ID_MATCH_ITEM_ID_PRICE, String.format("%s元", data.getPay_money()));
                holder.setText(RES_ID_MATCH_ITEM_ID_ADDRESS, data.getPlace_name());
                holder.setText(RES_ID_MATCH_ITEM_ID_TEAM_NAME, data.getCorps_name());
                holder.setText(RES_ID_MATCH_ITEM_GRADE, data.getCorps_grade());
                ImageUtil.loadUrl(context, data.getCategoryIcon(), R.drawable.ic_small_golf, (ImageView) holder.getView(RES_ID_MATCH_ITEM_ICON));
                ImageUtil.loadUrl(context, data.getCorps_icon(), R.drawable.temp_team_logo, (ImageView) holder.getView(RES_ID_MATCH_ITEM_TEAM_ICON));
                if (TextUtils.isEmpty(data.getCorps_grade())) {
                    holder.setVisibility(RES_ID_MATCH_ITEM_GRADE_ICON, View.GONE);
                } else if (data.getCorps_grade().equals("青铜战队")) {
                    holder.setBg(RES_ID_MATCH_ITEM_GRADE_ICON, R.drawable.ic_team_bronze);
                } else if (data.getCorps_grade().equals("白银战队")) {
                    holder.setBg(RES_ID_MATCH_ITEM_GRADE_ICON, R.drawable.ic_team_silver);
                } else if (data.getCorps_grade().equals("黄金战队")) {
                    holder.setBg(RES_ID_MATCH_ITEM_GRADE_ICON, R.drawable.ic_team_gold);
                } else if (data.getCorps_grade().equals("白金战队")) {
                    holder.setBg(RES_ID_MATCH_ITEM_GRADE_ICON, R.drawable.ic_team_platinum);
                }

//                gridView.setAdapter(new ArrayAdapter<EvaTagBean>(context, RES_ID_ROOT, evaluateArr) {
//                    @NonNull
//                    @Override
//                    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
//                        TextView textView = new TextView(context);
//
//                        if (evaluateArr.get(position).isSelect()) {
//                            textView.setTextColor(COLOR_YELLOW);
//                            textView.setBackgroundResource(DRAWABLE_YELLOW_BORDER);
//                        } else {
//                            textView.setTextColor(Color.WHITE);
//                            textView.setBackgroundResource(DRAWABLE_YELLOW_BTN);
//                        }
//
//                        textView.setTextSize(12);
//                        textView.setText(evaluateArr.get(position).getName());
//                        textView.setGravity(Gravity.CENTER);
//                        textView.setPadding(0, 0, 0, 0);
//                        textView.setMaxLines(1);
//                        return textView;
//                    }
//                });

                TagFlowLayout tagFlowLayout = holder.getView(RES_ID_MATCH_ITEM_EVALUATE);
                tagFlowLayout.setAdapter(new TagAdapter<EvaTagBean>(evaluateArr) {
                    @Override
                    public View getView(FlowLayout flowLayout, int i, EvaTagBean evaTagBean) {
                        TextView textView = new TextView(context);
                        textView.setText(evaTagBean.getName());
                        if (evaTagBean.isOwn()) {
                            textView.setTextColor(getResources().getColor(R.color.coloryellow));
                            textView.setBackgroundResource(R.drawable.yellow_border);
                        } else {
                            textView.setTextColor(getResources().getColor(R.color.white));
                            textView.setBackgroundResource(R.drawable.yellow_button_small);
                        }
                        return textView;
                    }
                });
                holder.getParentView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        FellowDetailActivity.startActivity(context, Type.TYPE_MATCH, data.getOrder_id());
                    }
                });
            }
        };

        areaList.add(new AreaBean(DEFAULT_AREA));
        areaAdapter = new ArrayAdapter<AreaBean>(context, RES_ID_ITEM_SPINNER_LAYOUT, areaList) {
            @Override
            public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                convertView = LayoutInflater.from(context).inflate(RES_ID_ITEM_SPINNER_DROP_DOWN_LAYOUT, null);
                TextView tv = (TextView) convertView;
                tv.setText(getItem(position).getArea());
                convertView.setPadding(0, 0, 0, d10);
                LinearLayout view = new LinearLayout(context);
                view.addView(convertView);
                view.setOrientation(LinearLayout.VERTICAL);
                ImageView imageView = new ImageView(context);
                imageView.setBackgroundResource(R.color.bg_color);
                imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 1));
                view.addView(imageView);
                view.setPadding(d10, d10, d10, 0);
                return view;
            }

            @NonNull
            @Override
            public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                convertView = LayoutInflater.from(context).inflate(RES_ID_ITEM_SPINNER_LAYOUT, null);
                TextView tv = (TextView) convertView.findViewById(RES_ID_ITEM_SPINNER_TV);
                tv.setText(getItem(position).getArea());
                return convertView;
            }
        };
        spArea.setAdapter(areaAdapter);
        spinnerHeight(spArea);
        CategoryBean defaultCategory = new CategoryBean();
        defaultCategory.setTitle(DEFAULT_SPORT_TYPE);
        typeSelectorList.add(defaultCategory);
        typeSelectorAdapter = new ArrayAdapter<CategoryBean>(context, RES_ID_ITEM_SPINNER_LAYOUT, typeSelectorList) {
            @Override
            public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                convertView = LayoutInflater.from(context).inflate(RES_ID_ITEM_SPINNER_DROP_DOWN_LAYOUT, null);
                TextView tv = (TextView) convertView;
                tv.setText(getItem(position).getTitle());
                convertView.setPadding(0, 0, 0, d10);
                LinearLayout view = new LinearLayout(context);
                view.addView(convertView);
                view.setOrientation(LinearLayout.VERTICAL);
                ImageView imageView = new ImageView(context);
                imageView.setBackgroundResource(R.color.bg_color);
                imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 1));
                view.addView(imageView);
                view.setPadding(d10, d10, d10, 0);
                return view;
            }

            @NonNull
            @Override
            public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                convertView = LayoutInflater.from(context).inflate(RES_ID_ITEM_SPINNER_LAYOUT, null);
                TextView tv = (TextView) convertView.findViewById(RES_ID_ITEM_SPINNER_TV);
                tv.setText(getItem(position).getTitle());
                return convertView;
            }
        };

        spType.setAdapter(typeSelectorAdapter);
        spinnerHeight(spType);
        typeAdapter = new QuickAdapter<CategoryBean>(context, RES_ID_TYPE_ITEM, typeList) {
            @Override
            public void bindData4View(ViewHolder holder, final CategoryBean data, int pos) {
                holder.setImg(context, RES_ID_TYPE_ITEM_IV, data.getIcon());
                holder.setText(RES_ID_TYPE_ITEM_TV, data.getTitle());
                holder.setVisibility(RES_ID_TYPE_ITEM_IV, View.VISIBLE);
                holder.getView(RES_ID_TYPE_ITEM_LL).setPadding(d5, d5, d5, d5);
                holder.getParentView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        switch (dialogSelectedType) {
                            case Type.TYPE_FELLOW:
                                SelectStoreActivity.startActivity(context, data.getId(), Type.RESERVATION_TYPE_FELLOW);
                                break;
                            case Type.TYPE_MATCH:
                                SelectStoreActivity.startActivity(context, data.getId(), Type.RESERVATION_TYPE_MATCH);
                                break;
                        }
                        typeDialog.dismiss();
                    }
                });
            }
        };

        timeAdapter = new ArrayAdapter<GlobeBean.Tag>(context, RES_ID_ITEM_SPINNER_LAYOUT, timeList) {
            @Override
            public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                convertView = LayoutInflater.from(context).inflate(RES_ID_ITEM_SPINNER_DROP_DOWN_LAYOUT, null);
                TextView tv = (TextView) convertView;
                tv.setText(getItem(position).getName());
                convertView.setPadding(0, 0, 0, d10);
                LinearLayout view = new LinearLayout(context);
                view.addView(convertView);
                view.setOrientation(LinearLayout.VERTICAL);
                ImageView imageView = new ImageView(context);
                imageView.setBackgroundResource(R.color.bg_color);
                imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 1));
                view.addView(imageView);
                view.setPadding(d10, d10, d10, 0);
                return view;
            }

            @NonNull
            @Override
            public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                convertView = LayoutInflater.from(context).inflate(RES_ID_ITEM_SPINNER_LAYOUT, null);
                TextView tv = (TextView) convertView.findViewById(RES_ID_ITEM_SPINNER_TV);
                tv.setText(getItem(position).getName());
                return convertView;
            }
        };
        spTime.setAdapter(timeAdapter);
    }

    private void removeMessageView(final View view) {
        TranslateAnimation animation = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0,
                Animation.RELATIVE_TO_SELF, -1,
                Animation.RELATIVE_TO_SELF, 0,
                Animation.RELATIVE_TO_SELF, 0);
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                messageList.remove(0);
                dataPanel.removeView(view);
                if (messageList.size() > 0) {
                    Message msg = new Message();
                    msg.what = WHAT_DILL_ADDED_MESSAGE;
                    msg.obj = messageList.get(0).obj;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        animation.setDuration(300);
        view.startAnimation(animation);
        animation.start();

    }

    private void addMessageView() {
        if (dataPanel != null && dataPanel.getChildCount() == 1) {
            final View view = LayoutInflater.from(context).inflate(RES_ID_MESSAGE_LAYOUT, null);
            final MatchBean.Item item = (MatchBean.Item) messageList.get(0).obj;
            ImageUtil.loadUrl(context, item.getCategoryIcon(), R.drawable.ic_small_golf, (ImageView) view.findViewById(RES_ID_MESSAGE_CATOGERY));
            ((TextView) view.findViewById(RES_ID_MESSAGE_NAME)).setText(item.getStadiumname());
            ((TextView) view.findViewById(RES_ID_MESSAGE_ADDRESS)).setText(item.getPlace_name());
            ((TextView) view.findViewById(RES_ID_MESSAGE_TIME)).setText(StringUtils.timeStamp10ToDate(item.getStime(), "yyyy-MM-dd") + "\n"
                    + StringUtils.timeStamp10ToDate(item.getStime(), "HH:mm"));
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    FellowDetailActivity.startActivity(context, currentType, item.getOrder_id());
                }
            });
            dataPanel.addView(view, 0);
            TranslateAnimation animation = new TranslateAnimation(
                    Animation.RELATIVE_TO_SELF, 1,
                    Animation.RELATIVE_TO_SELF, 0,
                    Animation.RELATIVE_TO_SELF, 0,
                    Animation.RELATIVE_TO_SELF, 0);
            animation.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {

                }

                @Override
                public void onAnimationEnd(Animation animation) {

                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
            animation.setDuration(300);
            view.startAnimation(animation);
            animation.start();

            new Thread() {
                @Override
                public void run() {
                    super.run();
                    try {
                        sleep(3 * 1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Message message = new Message();
                    message.what = WHAT_CLEAR_MESSAGE;
                    message.obj = view;
                    handler.sendMessage(message);
                }
            }.start();
        }

    }

    //填充时间筛选
    private void fillTimeSpinner() {
        for (int i = 1; i <= 5; i++) {
            GlobeBean.Tag tag = new GlobeBean.Tag();
            tag.setId(i + "");
            switch (i) {
                case 1:
                    tag.setName("全部订单");
                    break;
                case 2:
                    tag.setName("今天");
                    break;
                case 3:
                    tag.setName("三天内");
                    break;
                case 4:
                    tag.setName("一周内");
                    break;
                case 5:
                    tag.setName("两周内");
                    break;
            }
            timeList.add(tag);
        }
    }


    @OnItemSelected(RES_ID_FILTER_TIME)
    public void OnItemSelectedForTime(View view, int i) {
        time = getTime(timeList.get(i));
        pageNo = 1;
        loadData(false);
    }

    @OnItemSelected(RES_ID_FILTER_AREA)
    public void OnItemSelectedForArea(int i) {
        if (i == 0) {
            area = "";
        } else {
            area = areaList.get(i).getAdcode();
        }
        pageNo = 1;
        loadData(false);
    }

    @OnItemSelected(RES_ID_FILTER_TYPE)
    public void OnItemSelectedForType(int i) {
        if (i == 0) {
            category_id = "";
        } else {
            category_id = typeList.get(i).getId();
        }
        pageNo = 1;
        loadData(false);
    }

    //获得时间值
    private String getTime(GlobeBean.Tag tag) {
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        if (tag.getId().equals("2")) {
            return dateFormat.format(calendar.getTime()) + " 23:59:59";
        } else if (tag.getId().equals("3")) {
            calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) + 3);
            return dateFormat.format(calendar.getTime()) + " 23:59:59";
        } else if (tag.getId().equals("4")) {
            calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) + 7);
            return dateFormat.format(calendar.getTime()) + " 23:59:59";
        } else if (tag.getId().equals("5")) {
            calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) + 14);
            return dateFormat.format(calendar.getTime()) + " 23:59:59";
        } else {
            return "";
        }
    }

    @Override
    protected void loadData(boolean loadMore) {
        super.loadData(loadMore);
        switch (currentType) {
            case Type.TYPE_FELLOW:
                listView.setAdapter(fellowAdapter);
                fellowAdapter.notifyDataSetChanged();
                currentType = Type.TYPE_FELLOW;
                break;
            case Type.TYPE_MATCH:
                currentType = Type.TYPE_MATCH;
                break;
        }
        getYPOrderList();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!isFirstRequst) {
            loadData();
        }
        isFirstRequst = false;
        getYPOrderListForTop();
    }

    @Override
    protected void initView() {
        super.initView();
        refreshLayout.setOnRefreshListener(this);
        listView.setAdapter(fellowAdapter);
        initDialog();
        getAreaList();
        getCategoryList();
    }

    private void initDialog() {
        typeDialog = new Dialog(context, FULL_SCREEN_STYLE);
        View dialogContentView = LayoutInflater.from(context).inflate(RES_ID_DIALOG, null);
        gvActiveType = (GridView) dialogContentView.findViewById(RES_ID_TYPE_GV);
        gvActiveType.setAdapter(typeAdapter);
        typeDialog.setContentView(dialogContentView);
        Window window = typeDialog.getWindow();
        window.setWindowAnimations(R.style.dialogAnim);
        WindowManager.LayoutParams wl = window.getAttributes();
        //根据x，y坐标设置窗口需要显示的位置
        wl.x = 0; //x小于0左移，大于0右移
        wl.y = 0; //y小于0上移，大于0下移
//            wl.alpha = 0.6f; //设置透明度
//            wl.gravity = Gravity.BOTTOM; //设置重力
        window.setAttributes(wl);
        dialogContentView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                typeDialog.dismiss();
            }
        });
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (!isVisibleToUser && hiddenPanel != null) {
            hiddenPanel.setVisibility(View.GONE);
        }

        if (!isVisibleToUser && flowButton != null) {
            flowButton.setVisibility(View.VISIBLE);
        }
    }

    @OnClick(RES_ID_FELLOW)
    public void toFellow() {
        dialogSelectedType = Type.TYPE_FELLOW;
        showDialog();
    }

    @OnClick({RES_ID_FELLOW_CB, RES_ID_FELLOW_FL})
    public void onFellowSelected() {
        cbFellow.setChecked(true);
        cbMatch.setChecked(false);
        currentType = Type.TYPE_FELLOW;
        listView.setAdapter(fellowAdapter);
        getYPOrderListForTop();
        loadData(false);
        flowButton.setText("拼");
    }

    @OnClick({RES_ID_MATCH_CB, RES_ID_MATCH_FL})
    public void onMatchSelected() {
        cbFellow.setChecked(false);
        cbMatch.setChecked(true);
        currentType = Type.TYPE_MATCH;
        listView.setAdapter(matchAdapter);
        pageNo = 1;
        getYPOrderListForTop();
        loadData(false);
        flowButton.setText("约");
    }

    @OnClick(RES_ID_MATCH)
    public void toMatch() {
        dialogSelectedType = Type.TYPE_MATCH;
        showDialog();
    }

    private void showDialog() {
        typeDialog.show();
    }

    @OnTouch(RES_ID_NEW_BTN)
    public boolean onBtnDrag(View view, MotionEvent event) {
        final int x = (int) event.getRawX();
        final int y = (int) event.getRawY();
        if (controlHeight == 0) {
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) view
                    .getLayoutParams();
            params.leftMargin = ScreenUtils.getScreenW() - params.width - params.rightMargin;
            parentHeight = mViewGroup.getHeight() - params.height;
            params.topMargin = mViewGroup.getHeight() - params.height - params.bottomMargin;
            params.rightMargin = 0;
            params.bottomMargin = 0;
            params.removeRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
            params.removeRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            view.setLayoutParams(params);
        }

        switch (event.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_DOWN:
                timestamp = System.currentTimeMillis();
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) view
                        .getLayoutParams();
                xDelta = x - params.leftMargin;
                yDelta = y - params.topMargin;
                controlHeight = params.height;
                break;
            case MotionEvent.ACTION_MOVE:
                timestamp = -1;
                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view
                        .getLayoutParams();
                int xDistance = x - xDelta;
                int yDistance = y - yDelta;

                //边界判定
                if (xDistance > ScreenUtils.getScreenW() - layoutParams.width) {
                    xDistance = ScreenUtils.getScreenW() - layoutParams.width;
                }

                if (xDistance < 0) {
                    xDistance = 0;
                }

                if (yDistance > parentHeight) {
                    yDistance = parentHeight;
                }

                if (yDistance < 0) {
                    yDistance = 0;
                }
                layoutParams.leftMargin = xDistance;
                layoutParams.topMargin = yDistance;
                view.setLayoutParams(layoutParams);
                break;
        }
        mViewGroup.invalidate();
        return false;
    }

    @OnClick(RES_ID_NEW_BTN)
    public void beginFellow() {
        if (timestamp > 0) {
//            hiddenPanel.setVisibility(View.VISIBLE);
//            flowButton.setVisibility(View.GONE);
            if (cbFellow.isChecked()) {
                dialogSelectedType = Type.TYPE_FELLOW;
                showDialog();
            } else {
                dialogSelectedType = Type.TYPE_MATCH;
                showDialog();
            }
        }
    }

    //获取区域列表
    private void getAreaList() {
        SignHelper signHelper = new SignHelper("");
        mAppHelper.apiService().getAreaList(signHelper.GetParameter("key")).enqueue(new BaseCallback<ApiResponse<List<AreaBean>>>() {
            @Override
            public void onSuccess(Call<ApiResponse<List<AreaBean>>> call, Response<ApiResponse<List<AreaBean>>> response) {
                areaList.clear();
                areaList.add(new AreaBean(DEFAULT_AREA));
                areaList.addAll(response.body().getData());
                areaAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(Call<ApiResponse<List<AreaBean>>> call, Throwable t) {
                super.onFailure(call, t);
            }
        });
    }

    //获取类型列表
    private void getCategoryList() {
        mAppHelper.apiService().getCategoryList("").enqueue(new BaseCallback<ApiResponse<List<CategoryBean>>>() {
            @Override
            public void onSuccess(Call<ApiResponse<List<CategoryBean>>> call, Response<ApiResponse<List<CategoryBean>>> response) {
                typeSelectorAdapter.clear();
                CategoryBean defaultCategory = new CategoryBean();
                defaultCategory.setTitle(DEFAULT_SPORT_TYPE);
                typeSelectorAdapter.add(defaultCategory);
                typeSelectorAdapter.addAll(response.body().getData());
                typeSelectorAdapter.notifyDataSetChanged();

                typeList.clear();
                typeList.addAll(response.body().getData());
                typeAdapter.notifyDataSetChanged();
            }

        });
    }

    //类型13：约战，14：拼单
    private void getYPOrderList() {
        mAppHelper.apiService().getYPOrderList(currentType + "", time, area, category_id, Type.ORDER_YP_LIST).enqueue(new BaseCallback<ApiResponse<FellowListResponseBean>>() {
            @Override
            public void onSuccess(Call<ApiResponse<FellowListResponseBean>> call, Response<ApiResponse<FellowListResponseBean>> response) {
                refreshLayout.setRefreshing(false);
                int total = StringUtils.toInt(response.body().getData().getTotal());
                int current = StringUtils.toInt(response.body().getData().getCurrent_page());
                int per_page = StringUtils.toInt(response.body().getData().getPer_page());
                if (total <= current * per_page) {
                    refreshLayout.setDirection(SwipyRefreshLayoutDirection.TOP);
                } else {
                    refreshLayout.setDirection(SwipyRefreshLayoutDirection.BOTH);
                }
                if (currentType == Type.TYPE_MATCH) {
                    if (pageNo == 1) {
                        matchList.clear();
                    }
                    if (pageNo == current) {
                        matchList.addAll(MatchBean.dataChange(response.body().getData().getData()));
                        matchAdapter.notifyDataSetChanged();
                    }
                } else if (currentType == Type.TYPE_FELLOW) {
                    if (pageNo == 1) {
                        fellowList.clear();
                    }
                    if (pageNo == current) {
                        fellowList.addAll(MatchBean.dataChange(response.body().getData().getData()));
                        fellowAdapter.notifyDataSetChanged();
                    }
                }
            }

            @Override
            public void onError(Call<ApiResponse<FellowListResponseBean>> call, Throwable t) {
                super.onError(call, t);
                refreshLayout.setRefreshing(false);
            }

            @Override
            public void onTokenTimeOut() {
                refreshLayout.setRefreshing(false);
                super.onTokenTimeOut();
            }
        });
    }

    //类型13：约战，14：拼单
    private void getYPOrderListForTop() {
        SignHelper signHelper = new SignHelper("");
        mAppHelper.apiService().getYPOrderList(currentType + "", time, area, category_id, Type.ORDER_YP_PERSON).enqueue(new BaseCallback<ApiResponse<FellowListResponseBean>>() {
            @Override
            public void onSuccess(Call<ApiResponse<FellowListResponseBean>> call, Response<ApiResponse<FellowListResponseBean>> response) {
                List<MatchBean.Item> itemList = (List<MatchBean.Item>) MatchBean.dataChange(response.body().getData().getData());
                messageList.clear();
                if (itemList != null && itemList.size() > 0) {
                    Message message = new Message();
                    message.what = WHAT_NEW_MESSAGE;
                    for (int i = 0; i < itemList.size(); i++) {
                        Message msg = new Message();
                        msg.obj = itemList.get(i);
                        messageList.add(msg);
                    }
                    handler.sendMessage(message);
                }
            }
        });
    }

    public void reset() {
        typeDialog.dismiss();
        flowButton.setVisibility(View.VISIBLE);
        hiddenPanel.setVisibility(View.GONE);
    }

    //设置spinner下拉框高度
    private void spinnerHeight(Spinner spinner) {
        try {
            Field popup = Spinner.class.getDeclaredField("mPopup");
            popup.setAccessible(true);

            // Get private mPopup member variable and try cast to ListPopupWindow
            android.widget.ListPopupWindow popupWindow = (android.widget.ListPopupWindow) popup.get(spinner);

            // Set popupWindow height to 500px
            popupWindow.setHeight(600);
        } catch (NoClassDefFoundError | ClassCastException | NoSuchFieldException | IllegalAccessException e) {
            // silently fail...
        }
    }
}
